import React, { useRef, useMemo } from 'react';
import ReactQuill, { Quill } from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import quillEmoji from 'quill-emoji';
import "quill-emoji/dist/quill-emoji.css";
import { ImageDrop } from 'quill-image-drop-module';
import { message } from 'antd';
import './quillEditor.css';

const { EmojiBlot, ShortNameEmoji, ToolbarEmoji, TextAreaEmoji } = quillEmoji;
Quill.register({
  'formats/emoji': EmojiBlot,
  // 'formats/video': VideoBlot,
  'modules/emoji-shortname': ShortNameEmoji,
  'modules/emoji-toolbar': ToolbarEmoji,
  'modules/emoji-textarea': TextAreaEmoji,
  'modules/ImageDrop': ImageDrop,
}, true);

export default function QuillEditor({ videoLabel = false, imageLabel = true, ...props }) {
  const quillRef = useRef();

  const appendFile = (type, url) => {
    let quill = quillRef.current.getEditor();
    const cursorPosition = quill.getSelection().index;
    quill.insertEmbed(cursorPosition, type, url);
    quill.setSelection(cursorPosition + 1);
  };

  // 根据文件类型检查支持的文件和大小
  const isSupportFiles = (input, fileType) => {
    if (input.files.length === 0) {
      return false;
    }

    let maxSizeInMB = fileType === 'image' ? 2 : 20; // 图片2MB, 视频20MB
    let acceptFiles = fileType === 'image' ? ["jpeg", "jpg", "png", "gif", "bmp", "tiff", "webp", "heif", "jfif"] 
                                           : ["avi", "mp4", "mov", "wmv", "flv", "mkv", "mpg", "rmvb"];
    let formatError = [];
    let sizeError = [];

    input.files.forEach((file) => {
      const fileSizeInMB = file.size / 1024 / 1024;
      const fileExtension = file.name.split('.').pop().toLowerCase();
      if (!acceptFiles.includes(fileExtension)) {
        formatError.push(file.name);
      } else if (fileSizeInMB > maxSizeInMB) {
        sizeError.push(file.name);
      }
    });

    if (formatError.length > 0) {
      message.error(`文件格式只支持(${acceptFiles.join(", ")}):【${formatError.join(", ")}】`, 5);
      return false;
    }

    if (sizeError.length > 0) {
      message.error(`文件大小超出限制(${maxSizeInMB}MB):【${sizeError.join(", ")}】`, 5);
      return false;
    }

    return true;
  };

  const imageHandler = () => {
    const input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', ".jpg, .jpeg, .png, .gif, .bmp, .tiff, .webp, .heif, .jfif");
    input.setAttribute('multiple', 'multiple');
    input.click();
    input.onchange = () => {
      if (!isSupportFiles(input, 'image')) {
        return false;
      }
      props.onFileUpload && props.onFileUpload(input.files)
        .then(url => appendFile("image", url));
    };
  };

  const videoHandler = () => {
    const input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', ".avi, .mp4, .mov, .wmv, .flv, .mkv, .mpg, .rmvb");
    input.setAttribute('multiple', 'multiple');
    input.click();
    input.onchange = () => {
      if (!isSupportFiles(input, 'video')) {
        return false;
      }
      props.onFileUpload && props.onFileUpload(input.files)
        .then(url => appendFile("video", url));
    };
  };

  const quillModules = useMemo(() => {
    let containerLabels = ['link'];
    let modulesConfig = {
      toolbar: {
        container: [
          [{ 'header': [1, 2, 3, 4, 5, 6, false] }], //标题字号，不能设置单个字大小
          [{ 'size': ['small', false, 'large', 'huge'] }], //字体设置
          ['bold', 'italic', 'underline', 'strike'],
          [{ 'list': 'ordered' }, { 'list': 'bullet' }, { 'indent': '-1' }, { 'indent': '+1' }],
          // ['link', 'image', 'video'], // a链接和图片的显示
          containerLabels,
          [{ 'align': [] }],
          [{
            'background': ['rgb(  0,   0,   0)', 'rgb(230,   0,   0)', 'rgb(255, 153,   0)',
              'rgb(255, 255,   0)', 'rgb(  0, 138,   0)', 'rgb(  0, 102, 204)',
              'rgb(153,  51, 255)', 'rgb(255, 255, 255)', 'rgb(250, 204, 204)',
              'rgb(255, 235, 204)', 'rgb(255, 255, 204)', 'rgb(204, 232, 204)',
              'rgb(204, 224, 245)', 'rgb(235, 214, 255)', 'rgb(187, 187, 187)',
              'rgb(240, 102, 102)', 'rgb(255, 194, 102)', 'rgb(255, 255, 102)',
              'rgb(102, 185, 102)', 'rgb(102, 163, 224)', 'rgb(194, 133, 255)',
              'rgb(136, 136, 136)', 'rgb(161,   0,   0)', 'rgb(178, 107,   0)',
              'rgb(178, 178,   0)', 'rgb(  0,  97,   0)', 'rgb(  0,  71, 178)',
              'rgb(107,  36, 178)', 'rgb( 68,  68,  68)', 'rgb( 92,   0,   0)',
              'rgb(102,  61,   0)', 'rgb(102, 102,   0)', 'rgb(  0,  55,   0)',
              'rgb(  0,  41, 102)', 'rgb( 61,  20,  10)']
          }],
          [{
            'color': ['rgb(  0,   0,   0)', 'rgb(230,   0,   0)', 'rgb(255, 153,   0)',
              'rgb(255, 255,   0)', 'rgb(  0, 138,   0)', 'rgb(  0, 102, 204)',
              'rgb(153,  51, 255)', 'rgb(255, 255, 255)', 'rgb(250, 204, 204)',
              'rgb(255, 235, 204)', 'rgb(255, 255, 204)', 'rgb(204, 232, 204)',
              'rgb(204, 224, 245)', 'rgb(235, 214, 255)', 'rgb(187, 187, 187)',
              'rgb(240, 102, 102)', 'rgb(255, 194, 102)', 'rgb(255, 255, 102)',
              'rgb(102, 185, 102)', 'rgb(102, 163, 224)', 'rgb(194, 133, 255)',
              'rgb(136, 136, 136)', 'rgb(161,   0,   0)', 'rgb(178, 107,   0)',
              'rgb(178, 178,   0)', 'rgb(  0,  97,   0)', 'rgb(  0,  71, 178)',
              'rgb(107,  36, 178)', 'rgb( 68,  68,  68)', 'rgb( 92,   0,   0)',
              'rgb(102,  61,   0)', 'rgb(102, 102,   0)', 'rgb(  0,  55,   0)',
              'rgb(  0,  41, 102)', 'rgb( 61,  20,  10)']
          }],
          ['clean'], //清空
          ['emoji'], //emoji表情，设置了才能显示
        ],
        handlers: {}
      },
      ImageDrop: false,//是否支持拖拽图片
      'emoji-toolbar': true, // 是否展示 Emoji 工具栏
      "emoji-textarea": false, // 是否在文本框显示 Emoji
      "emoji-shortname": true, // 使用简短名称的 Emoji
    };

    if (imageLabel) {
      containerLabels.push("image");
      modulesConfig.toolbar.handlers["image"] = imageHandler;
    }
    if (videoLabel) {
      containerLabels.push("video");
      modulesConfig.toolbar.handlers["video"] = videoHandler;
    }
    return modulesConfig;
  }, [videoLabel, imageLabel]);

  const onChange = (content, delta, source, editor) => {
    if (content === "<p><br></p>") {
      props.onChange && props.onChange("", delta, source, editor);
    } else {
      props.onChange && props.onChange(content, delta, source, editor);
    }
  };

  return <ReactQuill ref={quillRef} modules={quillModules} theme="snow" {...props} onChange={onChange} />;
}